package com.yjkf.zh.admin.controller;

import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.iot.model.v20180120.InvokeDataAPIServiceRequest;
import com.aliyuncs.iot.model.v20180120.InvokeDataAPIServiceResponse;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;
import com.yjkf.zh.admin.aspect.LogAnnotation;
import com.yjkf.zh.admin.dao.SysCollectMapper;
import com.yjkf.zh.admin.dao.SysDeviceMapper;
import com.yjkf.zh.admin.dao.SysProductMapper;
import com.yjkf.zh.admin.dao.SysUserDeviceMapper;
import com.yjkf.zh.admin.model.*;
import com.yjkf.zh.admin.service.SysAliyunIotService;
import com.yjkf.zh.admin.service.SysDeviceCollectService;
import com.yjkf.zh.admin.service.SysPointUnitService;
import com.yjkf.zh.admin.util.SysConstant;
import com.yjkf.zh.core.http.HttpResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("deviceIot")
public class SysDeviceIotController {

    @Autowired
    private SysUserDeviceMapper sysUserDeviceMapper;

    @Autowired
    private SysDeviceMapper sysDeviceMapper;

    @Autowired
    private SysProductMapper sysProductMapper;

    @Autowired
    private SysAliyunIotService sysAliyunIotService;

    @Autowired
    private SysDeviceCollectService sysDeviceCollectService;

    @Autowired
    private SysCollectMapper sysCollectMapper;

    @Autowired
    private SysPointUnitService sysPointUnitService;

    String accessKey = SysConstant.AccessKey;
    String accessSecret = SysConstant.AccessSecret;
    String regionId = SysConstant.regionId;

    //这是利用阿里云物联网平台数据分析SDK查询的
    @GetMapping(value = "/selectIotApi")
   // @LogAnnotation(content = "查看设备历史数据")
    public HttpResult iotdb(@RequestParam Long id, @RequestParam String startTime, @RequestParam String endTime) {
        //    System.out.println("hello-------");
        if (id != null) {
            SysUserDevice sysUserDevice = sysUserDeviceMapper.findPointNum(id);

            String deviceName = sysUserDevice.getDeviceName();
            //根据设备id获取productKey
            SysProduct sysProduct = sysProductMapper.findProductKey(sysUserDevice.getDeviceId());

            String biaoshi = sysProduct.getProductKey();
            List<Map<Object, Object>> result = null;
            try {
                //   String accessKey = SysConstant.AccessKey;
                //   String accessSecret = SysConstant.AccessSecret;
                DefaultProfile.addEndpoint(regionId, regionId, "Iot", "iot.cn-shanghai.aliyuncs.com");
                IClientProfile profile = DefaultProfile.getProfile(regionId, accessKey, accessSecret);
                DefaultAcsClient client = new DefaultAcsClient(profile); //初始化SDK客户端
                //    String biaoshi = "ARV1";
                String apiSrn = "acs:iot:*:1150762710362502:serveapi/";
                String api = apiSrn + biaoshi;
                InvokeDataAPIServiceRequest.Param param = new InvokeDataAPIServiceRequest.Param();
                InvokeDataAPIServiceRequest.Param param1 = new InvokeDataAPIServiceRequest.Param();
                InvokeDataAPIServiceRequest.Param param2 = new InvokeDataAPIServiceRequest.Param();
                // 请求参数名称
                param.setParamName("device_name");
                param1.setParamName("stime");
                param2.setParamName("etime");
                // 请求参数值
                param.setParamValue(deviceName);
                param1.setParamValue(startTime);
                param2.setParamValue(endTime);
                InvokeDataAPIServiceRequest request = new InvokeDataAPIServiceRequest();
                request.setApiSrn(api);
                request.setParams(Arrays.asList(param, param1, param2));
                // 请求方法 POST
                request.setSysMethod(MethodType.POST);
                InvokeDataAPIServiceResponse response = client.getAcsResponse(request);
                // 服务API指定的SQL查询结果
                result = response.getData().getResultList();
            } catch (ClientException ce) {
                ce.printStackTrace();
            }
            if (result == null) {
                return null;
            } else {
                return HttpResult.ok(result);
            }
        } else {
            return HttpResult.error("暂无数据");
        }
    }

    /*
        @GetMapping(value = "/deviceInfo")
       // @LogAnnotation(content = "查看设备实时数据")
        public HttpResult snapDevice(@RequestParam Long id, HttpServletRequest request1) {

            if(id==null||id==0){
                Long userId = (Long)request1.getSession().getAttribute("userId");

                List<SysUserDevice> sysUserDevices = sysUserDeviceMapper.findByUserId(userId);
                if(sysUserDevices.isEmpty()){
                    return HttpResult.error("false!");
                }
                SysUserDevice sysUserDevice = sysUserDevices.get(0);
                id=sysUserDevice.getId();
            }
            SysUserDevice sysUserDevice = sysUserDeviceMapper.findPointNum(id);
            if(sysUserDevice==null){
                return HttpResult.error("暂无数据");
            }
            String deviceName = sysUserDevice.getDeviceName();
            //根据设备id获取productKey
            SysProduct sysProduct = sysProductMapper.findProductKey(sysUserDevice.getDeviceId());


            String biaoshi = sysProduct.getProductKey();

            List<Map<Object, Object>> result = null;
            try {
              //  String accessKey = SysConstant.AccessKey;
             //   String accessSecret = SysConstant.AccessSecret;
                DefaultProfile.addEndpoint(regionId, regionId, "Iot", "iot.cn-shanghai.aliyuncs.com");
                IClientProfile profile = DefaultProfile.getProfile(regionId, accessKey, accessSecret);
                DefaultAcsClient client = new DefaultAcsClient(profile); //初始化SDK客户端
                //    String biaoshi = "ARV1";
                String apiSrn = "acs:iot:*:1150762710362502:serveapi/";
                String api = apiSrn + biaoshi+"snap";
                InvokeDataAPIServiceRequest.Param param = new InvokeDataAPIServiceRequest.Param();

                // 请求参数名称
                param.setParamName("device_name");

                // 请求参数值
                param.setParamValue(deviceName);
                InvokeDataAPIServiceRequest request = new InvokeDataAPIServiceRequest();
                request.setApiSrn(api);
                request.setParams(Arrays.asList(param));
                // 请求方法 POST
                request.setSysMethod(MethodType.POST);
                InvokeDataAPIServiceResponse response = client.getAcsResponse(request);
                // 服务API指定的SQL查询结果
                result = response.getData().getResultList();
                System.out.println(result);
            } catch (ClientException ce) {
                ce.printStackTrace();
            }
            if (result == null) {
                return null;
            } else {
                return HttpResult.ok(result);
            }
        }
    */
    //根据设备名称查询设备状态
    @GetMapping("/getDeviceStatus")
    public HttpResult getDeviceStatus(@RequestParam Long id, HttpServletRequest request1) {
        if (id == null || id == 0) {
            Long userId = (Long) request1.getSession().getAttribute("userId");
            List<SysUserDevice> sysUserDevices = sysUserDeviceMapper.findByUserId5(userId);
            if (sysUserDevices.isEmpty()) {
                return HttpResult.error();
            }
            SysUserDevice sysUserDevice = sysUserDevices.get(0);
            id = sysUserDevice.getId();
        }
        SysUserDevice sysUserDevice = sysUserDeviceMapper.findPointNum(id);
        if (sysUserDevice == null) {
            return HttpResult.error("暂无数据");
        }
        String deviceName = sysUserDevice.getDeviceName();
        //根据设备id获取productKey
        SysProduct sysProduct = sysProductMapper.findProductKey(sysUserDevice.getDeviceId());


        String productKey = sysProduct.getProductKey();

        // String accessKey = SysConstant.AccessKey;
        //  String accessSecret = SysConstant.AccessSecret;

       /* DefaultProfile profile = DefaultProfile.getProfile(regionId, accessKey, accessSecret);
        IAcsClient client = new DefaultAcsClient(profile);

        CommonRequest request = new CommonRequest();
        request.setSysMethod(MethodType.GET);
        request.setSysDomain("iot.cn-shanghai.aliyuncs.com");
        request.setSysVersion("2018-01-20");
        request.setSysAction("GetDeviceStatus");
        request.putQueryParameter("RegionId", "cn-shanghai");
        request.putQueryParameter("ProductKey", productKey);
        request.putQueryParameter("DeviceName", deviceName);
        Object result = null;
        try {
            CommonResponse response = client.getCommonResponse(request);

            result = response.getData();
            System.out.println(result);
        } catch (ServerException e) {
            e.printStackTrace();
        } catch (ClientException e) {
            e.printStackTrace();
        }*/
       String action = "GetDeviceStatus";
        return HttpResult.ok(sysAliyunIotService.aliyunIotService(productKey,deviceName,action));
    }


    @GetMapping(value = "/deviceInfo")
    // @LogAnnotation(content = "查看设备实时数据")
    public HttpResult queryDeviceProperty(@RequestParam Long id, HttpServletRequest request1) {
        if (id == null || id == 0) {
            Long userId = (Long) request1.getSession().getAttribute("userId");

            List<SysUserDevice> sysUserDevices = sysUserDeviceMapper.findByUserId1(userId);
            if (sysUserDevices.isEmpty()) {
                return HttpResult.error("false!");
            }
            SysUserDevice sysUserDevice = sysUserDevices.get(0);

            id = sysUserDevice.getId();
        }
        //根据id获取用户父类信息
        SysUserDevice sysUserDevi=  sysUserDeviceMapper.findById(id);
        SysUserDevice sysUserDevice = sysUserDeviceMapper.findPointNum(sysUserDevi.getParentDeviceId());
        if (sysUserDevice == null) {
            return HttpResult.error("暂无数据");
        }
        String deviceName = sysUserDevice.getDeviceName();
        //根据设备id获取productKey
        SysProduct sysProduct = sysProductMapper.findProductKey(sysUserDevice.getDeviceId());
        String productKey = sysProduct.getProductKey();
     /*   DefaultProfile profile = DefaultProfile.getProfile("cn-shanghai", accessKey, accessSecret);
        IAcsClient client = new DefaultAcsClient(profile);
        CommonRequest request = new CommonRequest();
        request.setSysMethod(MethodType.GET);
        request.setSysDomain("iot.cn-shanghai.aliyuncs.com");
        request.setSysVersion("2018-01-20");
        request.setSysAction("QueryDevicePropertyStatus");
        request.putQueryParameter("RegionId", regionId);
        request.putQueryParameter("ProductKey", productKey);
        request.putQueryParameter("DeviceName", deviceName);
        Object result = null;
        try {
            CommonResponse response = client.getCommonResponse(request);
            result = response.getData();
            System.out.println(result);
        } catch (ServerException e) {
            e.printStackTrace();
        } catch (ClientException e) {
            e.printStackTrace();
        }*/

        String action="QueryDevicePropertyStatus";
        return HttpResult.ok(sysAliyunIotService.aliyunIotService(productKey,deviceName,action));
       // return HttpResult.ok(result);
    }

    @GetMapping("/batchDeviceState")
    public HttpResult batchDeviceState( HttpServletRequest request1){
        Long userId = (Long) request1.getSession().getAttribute("userId");
        //获取productKey
        //获取设备列表名deviceName
        List<SysUserDevice> sysUserDevices = sysUserDeviceMapper.findByUserId4(userId);

        SysProduct sysProduct = sysProductMapper.findProductKey(sysUserDevices.get(0).getDeviceId());
        String productKey = sysProduct.getProductKey();

        DefaultProfile profile = DefaultProfile.getProfile("cn-shanghai", accessKey, accessSecret);
        IAcsClient client = new DefaultAcsClient(profile);
        CommonRequest request = new CommonRequest();
        request.setSysMethod(MethodType.GET);
        request.setSysDomain("iot.cn-shanghai.aliyuncs.com");
        request.setSysVersion("2018-01-20");
        request.setSysAction("BatchGetDeviceState");
        request.putQueryParameter("RegionId", "cn-shanghai");
        request.putQueryParameter("ProductKey", productKey);
        int i = 0 ;
        for(SysUserDevice sysUserDevice:sysUserDevices) {
            i++;
            request.putQueryParameter("DeviceName."+i, sysUserDevice.getDeviceName());
        }
        Object result2 = null;
        try {
            CommonResponse response = client.getCommonResponse(request);
            result2 = response.getData();
        } catch (ServerException e) {
            e.printStackTrace();
        } catch (ClientException e) {
            e.printStackTrace();
        }
        return HttpResult.ok(result2);
    }

    @GetMapping(value="/devicels")
    public HttpResult findDeviceLs(@RequestParam Long collectId, @RequestParam String startTime, @RequestParam String endTime,@RequestParam int num, HttpServletRequest request1){
        Long userId = (Long) request1.getSession().getAttribute("userId");
        //根据用户Id、收藏组名获取变量列表
        List<SysDeviceCollect> sysDeviceCollectList = sysDeviceCollectService.findTableData(collectId,userId);
        //根据collectId获取用户设备Id
        SysCollect sysCollect = sysCollectMapper.collectTime(collectId);
        Long userDeviceId = sysCollect.getUserDeviceId();
        //根据用户设备Id获取设备Id
        SysUserDevice sysUserDevice = sysUserDeviceMapper.getDeviceId(userDeviceId);
        String deviceName ="";
        String productKey ="";
        Long deviceId = 0L;
        if(sysUserDevice.getType()==1L){
            Long parentDeviceId = sysUserDevice.getParentDeviceId();
            SysUserDevice sysUserDevicee = sysUserDeviceMapper.getDeviceId(parentDeviceId);
            deviceId = sysUserDevicee.getDeviceId();
        }else{
            deviceId = sysUserDevice.getDeviceId();
        }

            //根据DeviceId获取deviceName与prodectKey
            SysDevice sysDevice = sysDeviceMapper.findDevice(deviceId);
            deviceName = sysDevice.getDeviceName();
            Long productId = sysDevice.getProductId();
            //根据productId获取productKey
            SysProduct sysProduct = sysProductMapper.selectKeyForId(productId);
            productKey = sysProduct.getProductKey();
        DefaultProfile profile = DefaultProfile.getProfile("cn-shanghai", accessKey, accessSecret);
        IAcsClient client = new DefaultAcsClient(profile);
        CommonRequest request = new CommonRequest();
        request.setSysMethod(MethodType.GET);
        request.setSysDomain("iot.cn-shanghai.aliyuncs.com");
        request.setSysVersion("2018-01-20");
        request.setSysAction("QueryDevicePropertiesData");
        request.putQueryParameter("RegionId", "cn-shanghai");
        request.putQueryParameter("ProductKey", productKey);
        request.putQueryParameter("DeviceName", deviceName);
        request.putQueryParameter("StartTime", startTime);
        int i=0;
        for(SysDeviceCollect sysDeviceCollect:sysDeviceCollectList){
            i++;
            request.putQueryParameter("Identifier."+i, sysDeviceCollect.getPointIdent());
        }
        request.putQueryParameter("Asc", "1");
        request.putQueryParameter("EndTime", endTime);
        request.putQueryParameter("PageSize", Integer.toString(num));
        System.out.println("num"+ Integer.toString(num));
        Object result = null;
        try {
            CommonResponse response = client.getCommonResponse(request);
            result = response.getData();
            System.out.println(result);
        } catch (ServerException e) {
            e.printStackTrace();
        } catch (ClientException e) {
            e.printStackTrace();
        }
        return HttpResult.ok(result);
    }

    @GetMapping(value="/devicelsForId")
    public HttpResult deviceLs(@RequestParam Long userDeviceId,@RequestParam String startTime, @RequestParam String endTime,@RequestParam int num, HttpServletRequest request1){
        Long userId = (Long) request1.getSession().getAttribute("userId");
        //根据userDeviceId获取设备Id
        SysUserDevice sysUserDevice = sysUserDeviceMapper.findPdfudi(userDeviceId);

        Long deviceId = sysUserDevice.getDeviceId();

        List<SysDevicePointUnit> sysDevicePointUnitList = sysPointUnitService.findAllById(userDeviceId,request1);

        //根据DeviceId获取deviceName与prodectKey
        SysDevice sysDevice = sysDeviceMapper.findDevice(deviceId);
        String  deviceName = sysDevice.getDeviceName();
        Long productId = sysDevice.getProductId();
        //根据productId获取productKey
        SysProduct sysProduct = sysProductMapper.selectKeyForId(productId);
        String productKey = sysProduct.getProductKey();
        DefaultProfile profile = DefaultProfile.getProfile("cn-shanghai", accessKey, accessSecret);
        IAcsClient client = new DefaultAcsClient(profile);
        CommonRequest request = new CommonRequest();
        request.setSysMethod(MethodType.GET);
        request.setSysDomain("iot.cn-shanghai.aliyuncs.com");
        request.setSysVersion("2018-01-20");
        request.setSysAction("QueryDevicePropertiesData");
        request.putQueryParameter("RegionId", "cn-shanghai");
        request.putQueryParameter("ProductKey", productKey);
        request.putQueryParameter("DeviceName", deviceName);
        request.putQueryParameter("StartTime", startTime);
        int i=0;
        for(SysDevicePointUnit sysDevicePointUnit:sysDevicePointUnitList){
            i++;
            System.out.println(sysDevicePointUnit.getPointIdent());
            request.putQueryParameter("Identifier."+i, sysDevicePointUnit.getPointIdent());
        }
        request.putQueryParameter("Asc", "1");
        request.putQueryParameter("EndTime", endTime);
        request.putQueryParameter("PageSize", Integer.toString(num));
        System.out.println("num"+ Integer.toString(num));
        Object result = null;
        try {
            CommonResponse response = client.getCommonResponse(request);
            result = response.getData();
            System.out.println(result);
        } catch (ServerException e) {
            e.printStackTrace();
        } catch (ClientException e) {
            e.printStackTrace();
        }
        return HttpResult.ok(result);
    }


}
